<template>
    <Layout>
        <div>
            <Form ref="form1" :model="form1" :label-width="120">
                <Row class="query-form" style="padding-top: 15px">
                    <Col span="8">
                        <FormItem label="标题：">
                            <Input class="query-form-el" type="text" v-model="form1.title"></Input>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="活动月份：">
                            <DatePicker class="query-form-el" v-model="sartDateQuery" format="yyyy-MM" type="month"
                                        placement="bottom-end"
                                        @on-change="dateChange"
                                        style="width: 100%;"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                    </Col>
                </Row>
                <Row class="query-form">
                    <Col span="24">
                        <Button size="large" type="success" class="ivu-btn-add" icon="md-add" @click="addArtical()">新增
                        </Button>
                    </Col>
                </Row>
            </Form>
        </div>
        <!-- 响应结果内容展示 -->
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" :loading="buttonLoading"
               stripe border :columns="columns1" :data="resultData">
        </Table>
        <!-- 底部分页条 -->
        <Page :total="dataCount" :page-size="pageSize"
              :page-size-opts="pageSizeArray" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" show-total show-sizer/>

        <!--弹出窗  @on-cancel="cancel":当点击取消触发的函数-->

        <Modal ref="modal1Ref" title="活动信息" :transfer=false v-model="model1" :width=1200 :styles="{height:'800px'}"  class-name='limit-height-dialog'>		
			<div id="main_content">
                <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" label-position="top">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem label="标题：" prop="title">
                                <Input type="text" v-model="formCustom.title"></Input>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex"  justify="space-around" class="code-row-bg">
                        <Col span="23">
                            <FormItem label="封面图片："  prop="fileName">
                                <Upload
                                        ref="upload"
                                        type="drag"
                                        multiple
                                        :show-upload-list="true"
                                        :before-upload="beforeUploadCover"
                                        :action="downloadUrl"
                                        :max-size="10240"
                                >
                                    <div style="padding: 20px 0">
                                        <Icon type="ios-cloud-upload" size="30" style="color: #3399ff"></Icon>
                                        <p> 请上传 jpg，jpeg，png 格式的图片</p>
                                    </div>
                                </Upload>
                                <div v-show="coverFileBeforeList.length>0" v-for="(item,index) in coverFileBeforeList" :key='item'>
                                    <a>{{ item.name }}</a>
                                    <Button type="text" icon="md-trash" @click="coverFileBeforeList.splice(index, 1)"
                                            style="margin-left: 5px;margin-bottom: 3px"/>
                                </div>
                                <div v-show="coverFileList.length>0" v-for="item in coverFileList" :key='item'>
                                    <a @click="downloadFile(formCustom.safeActivityMonthId,item)">{{ item.fileName }}</a>
                                    <Button type="text" icon="md-trash" @click="deleteCoverFile(item.id)"
                                            style="margin-left: 5px;margin-bottom: 3px"/>
                                </div>
                            </FormItem>
                        </Col>
                    </Row>  
                    <Row type="flex"  justify="center" class="code-row-bg">
                        <Col span="23">
                            <FormItem label="内容：" prop="content">
                                <quill-editor ref="myTextEditor" :options="editorOption" v-model="formCustom.content"  style="height:400px;"></quill-editor>
                            </FormItem>
                        </Col>
                    </Row> 
                    <Row type="flex" style="margin-top:60px;" justify="center" class="code-row-bg">
                        <Col span="23">
                            <FormItem label="活动视频上传：" prop="uploadList">
                                <div>
                                    <Upload ref="upload"
                                            :before-upload="beforeUpload"
                                            :show-upload-list="true"
                                            :max-size="10240"
                                            multiple
                                            type="drag"
                                            accept="application/mp4"
                                            :format="['mp4']"
                                            :action="fileUrl">
                                        <div style="padding: 10px">
                                            <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                            <p>点击将文件拖拽到这里上传</p>
                                            <span style="font-size:8px;color: #797a64">支持扩展名：.mp4</span>
                                        </div>
                                    </Upload>
                                </div>
                                <div v-show="uploadBeforeList.length>0" v-for="(item,index) in uploadBeforeList" :key='item'>
                                    <a>{{ item.name }}</a>
                                    <Button type="text" icon="md-trash" @click="uploadBeforeList.splice(index, 1)"
                                            style="margin-left: 5px;margin-bottom: 3px"/>
                                </div>
                                <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                    <a @click="downloadVideoFile(item.videoPath,item.videoFileName)">{{ item.videoFileName }}</a>
                                    <Button type="text" icon="md-trash" @click="deleteContentFile(item.id)"
                                            style="margin-left: 5px;margin-bottom: 3px"/>
                                </div>
                            </FormItem>
                        </Col>
                    </Row> 
                </Form>
            </div>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' @click="submit('formCustom')">确定</Button>
                <Button type="text" class='ivu-btn-cancel' @click="modalcancel">取消</Button>
            </div>
        </Modal>

        <Modal class="modal-view-detail" title="活动信息详情" :transfer=false v-model="model2" :width=1200 :styles="{height:'800px'}"  class-name='limit-height-dialog'>		
            <Row>
                <Col span="24">
                    <Form ref="showdata" :label-width="110" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="标题：" prop="title">
                                    {{formCustom.title}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="封面图片：">   
                                    <div v-show="coverFileList.length>0" v-for="item in coverFileList" :key='item'>
                                        <img :src="item.picture" style="width: 150px;height: 150px" />
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="内容：">
                                     <div v-html="formCustom.content"></div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="活动视频：">
                                <!--    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadVideoFile(item.videoPath,item.videoFileName)">{{ item.videoFileName }}</a>
                                    </div>   -->
                                    <div v-for="item in downloadUrls" >
                                        <iframe style="height:300px;width:100%" v-if='item' :src="item" ></iframe>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>

        <Modal class="modal-view-detail" title="通知公告审核"   :transfer=false   v-model="model3" :width=1200 :styles="{height:'800px'}"  class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="showdata" :label-width="110" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="标题：" prop="title">
                                    {{formCustom.title}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="发布人：" prop="userName">
                                    {{formCustom.createUserName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="发布时间：" prop="infoTitle">
                                    {{formCustom.createDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="封面图片：">   
                                    <div v-show="coverFileList.length>0" v-for="item in coverFileList" :key='item'>
                                        <img :src="item.picture" style="width: 150px;height: 150px" />
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="内容：">
                                     <div v-html="formCustom.content"></div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="活动视频：">
                                    <div v-for="item in downloadUrls" >
                                        <iframe style="height:300px;width:100%" v-if='item' :src="item" ></iframe>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="text"  style="margin-left:15px;" class='ivu-btn-save' @click="examineTop('formCustom')">通过并置顶</Button>
                <Button type="primary" class='ivu-btn-save' @click="examine('formCustom')">通过</Button>
                <Button type="text" class='ivu-btn-cancel' @click="reject('formCustom')">驳回</Button>
            </div>
        </Modal>
    </layout>

</template>

<script>
    import {Api} from "../../../api/index.js"
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import {formatDate,compressImg} from '@/tools/index'
    // require styles
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import {
        quillEditor
    } from 'vue-quill-editor'
    import * as Quill from 'quill'  // 引入编辑器
    import ImageResize from 'quill-image-resize-module';
    Quill.register('modules/imageResize',ImageResize);

    export default {
        components:{
            quillEditor
        },
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill;
            },
        },
        data() {
            return {
                currentUserId: "",
                uploadList: [],
                coverFileList: [],
                coverFileBeforeList: [],
                uploadFileDeleteList:[],
                coverFileDeleteList:[],
                fileUrl: Api.interestedPartiesUserFile,
                buttonLoading: false,
                downloadUrls:[],
                add: false,
                form1: {},
                formCustom: {},
                ruleCustom: {
                   /* ifTop: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                this.$Message.error("是否置顶不能为空")
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blue'
                    }],*/
                    topNumber: [{
                        validator: (rule, value, callback) => {
                            if (this.formCustom.ifTop==1&&(value == null || value == '' || value == undefined)) {
                                this.$Message.error("置顶级别不能为空")
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blue'
                    }],
                  noticeType: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    title: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                this.$Message.error("通知公告标题不能为空")
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blue'
                    }]
                },
                resultData: [],
                showdata: {},
                tableHeight: 450,
                pageSizeArray: [5, 10, 20, 50],
                dataCount: 0,
                pageSize: 10,
                currentPage: 1,
                columns1: [{
                    title: "序号",
                    width: 80,
                    align: "center",
                    render: (h, params) => {
                        return h('span', params.index + (this.currentPage - 1) * this.pageSize + 1);
                    }
                },
                {
                    title: '标题',
                    align: 'center',
                    minWidth: 300,
                    key: 'title'
                },
                {
                    title: '发布处室',
                    align: 'center',
                    minWidth: 300,
                    key: 'createOrgName'
                },
                {
                    title: '发布人',
                    align: 'center',
                    minWidth: 120,
                    key: 'createUserName'
                },
                {
                    title: '内容',
                    align: 'center',
                    ellipsis: true,
                    minWidth: 100,
                    key: 'content'
                },
                {
                    title: '发布时间',
                    align: 'center',
                    minWidth: 120,
                    key: 'createDate',
                    render: (h, params) => {
                            return h('span', (this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd')));
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    key: 'view',
                    fixed: 'right',
                    width: 250,
                    render: (h, params) => {
                        if(sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == 'e6512254eace4c7da4b6e22688e452re') == undefined
                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined){
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( this.currentUserId != params.row.createUserId && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) && sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '#d0d0d0' :'',
                                        pointerEvents: (this.currentUserId != params.row.createUserId && (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) && sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined) &&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '#d0d0d0' :'red',
                                        pointerEvents: (this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)&&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined ) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                        else{
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),    
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)&&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '#d0d0d0' :'',
                                        pointerEvents: (this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)&&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)&&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '#d0d0d0' :'red',
                                        pointerEvents: (this.currentUserId != params.row.createUserId&& (sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') == undefined)&&sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( params.row.isPass != '0') ? '#d0d0d0' :'red',
                                        pointerEvents: (params.row.isPass != '0') ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.verifyData(params.row);
                                        }
                                    }
                                }, '审核'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( params.row.isPass != '1') ? '#d0d0d0' :'red',
                                        pointerEvents: (params.row.isPass != '1') ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.recallData(params.row);
                                        }
                                    }
                                }, '撤回')
                            ]);
                        }
                    }
                }
                ],
                model1: false,
                model2: false,
                model3: false,
                infoId: "",
                uploadBeforeList:[],
                picture: '',
                fileName: null,
                downloadUrl: Api.downloadMongoFile,
                editorOption: {
                    placeholder: 'Hello World',
                    modules:{
                         toolbar: {
                            container:[
                                [{ 'size': ['small', false, 'large'] }],
                                [{ 'color': [] }, { 'background': [] }], 
                                [{ 'font': [] }],
                                [{ 'align': [] }],
                                ['bold', 'italic'],
                                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                                ['link', 'image'],
                                [{ 'direction': 'rtl' }],
                            ]
                        },
                       imageResize:{
                            displayStyles:{
                                backgroundColor:'black',
                                border:'none',
                                color:'white'
                            },
                            modules:['Resize','DisplaySize','Toolbar']
                        }
                    }
                }
            }
        },
        mounted: function () {
            this.currentUserId = sessionStorage('userId').getObject('userId').userId;
            this.tableHeight = window.innerHeight - 260;
            this.query();
        },
        methods: {
            query() {
                this.buttonLoading = true
                let data = {
                    startPage: this.currentPage,
                    size: this.pageSize,
                    orgId: sessionStorage('userId').getObject('userId').companyId
                };

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.safeActivityMonth + "/list";
                this.$http.get(url, {params: data}).then((res) => {
                    if (res.data.status == '200') {
                        this.resultData = res.data.data.data;
                        this.dataCount = res.data.data.totalSize;
                    } else {
                        this.$Message.error("数据获取失败")
                    }
                    this.buttonLoading = false
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            modalcancel() {
                this.model1 = false;
                this.formCustom = {};
                this.uploadBeforeList=[]
            },
            dataChange(date){
                this.form1.createTime = date;
            },
            getCoverFile() {
                let url = this.fileUrl + '/' + this.formCustom.safeActivityMonthId + '/files/picture';
                this.$http.get(url).then((res) => {
                    if (res.data.result == "success") {
                        this.coverFileList = res.data.data;
                    }
                })
            },
            getFiles() {
                this.downloadUrls = [];
                this.uploadList = [];
                if(this.formCustom.videoFileName!=null&&this.formCustom.videoPath!=null){
                    let names = this.formCustom.videoFileName.split("@")
                    let paths = this.formCustom.videoPath.split("@")
                    for(var i=0;i<names.length-1;i++){
                        this.uploadList.push({
                            videoFileName:names[i],
                            videoPath:paths[i]
                        })
                        this.downloadUrls.push(Api.courseVideoDownLoadUrl + paths[i]);
                    }
                }
            },
            beforeUpload(file) {
                this.uploadBeforeList.push(file)
                return false
            },
            beforeUploadCover(file) {
                if(this.coverFileBeforeList.length == 1){
                    this.$Message.error("封面图片只能上传一个文档，请先删除原有的再重新上传")
                    return false;
                }
                this.coverFileBeforeList.push(file);
                return false;
            },
            downloadFile(guideId, file) {
                let url = this.fileUrl + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            downloadVideoFile(path,fileName) {
                let url = Api.courseVideoDownload+"?filePath="+path;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            async contentFileSub(){
                this.formCustom.videoFileName = "";
                this.formCustom.videoPath = "";           
                for(var i=0;i<this.uploadBeforeList.length;i++){
                    let formData = new FormData();
                    formData.append("uploadFile", this.uploadBeforeList[i]);
                    this.formCustom.videoFileName += (this.uploadBeforeList[i].name + "@");
                    let url=Api.courseVideoUrl+'/video';
                    await this.$http.post(url, formData).then((res) => {
                        this.uploadBeforeList=[];
                        this.formCustom.videoPath += (res.data.filePath + "@");
                    })
                }
            },
            async coverFileSub(){
                let formData = new FormData();
                var compressFile =await compressImg(this.coverFileBeforeList[0]);
                formData.append("files", compressFile);
                 // 文件对象
                let url=Api.uploadMongoFileByKeyAndType+'/' + this.formCustom.safeActivityMonthId + '/files/picture';
                this.$http.post(url, formData).then((res) => {
                    this.coverFileBeforeList=[]
                })
            },
            submit() {
                this.$refs['formCustom'].validate(async(valid) => {
                    if (valid) {
                        let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                        let userId = sessionStorage('userId').getObject('userId').userId;
                        if (this.add) {
                            this.formCustom.createUserId = userId;
                            this.formCustom.createOrgId = orgId;
                            if (this.uploadBeforeList.length > 0) {
                                await this.contentFileSub()
                            }
                            if(this.coverFileBeforeList.length > 0){
                                await this.coverFileSub();
                            }
                            this.$http.post(Api.safeActivityMonth, this.formCustom).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        } else {
                            if (this.uploadFileDeleteList.length > 0) {
                                this.contentFileDel()
                            }
                            if(this.coverFileDeleteList.length > 0){
                                this.coverFileDel();
                            }
                            if (this.uploadBeforeList.length > 0) {
                                await this.contentFileSub()
                            }
                            if(this.coverFileBeforeList.length > 0){
                                await this.coverFileSub();
                            }
                            this.formCustom.updateUserId = userId;
                            this.formCustom.updateOrgId = orgId;
                            this.$http.put(Api.safeActivityMonth, this.formCustom).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }

                    } else {
                        // this.$Message.error('请填报完整!');
                    }
                })
            },
            addArtical() {
                this.uploadList = [];
                this.uploadBeforeList=[];
                this.coverFileBeforeList = [];
                this.coverFileList = [];
                this.add = true;
                this.model1 = true;
                
                this.formCustom = {
                    ifTop:1,
                    topNumber:1,
                    type:1,
                    safeActivityMonthId: this.get_uuid(),
                }
            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                return a;
            },
            //重置输入框
            reset() {
                this.form1 = {};
            },
            pageChange(pageNum) {
                this.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pageSize = pageSize;
                this.query();
            },
            showData(data, flag) {
                this.uploadBeforeList=[]
                this.uploadList=[]
                this.coverFileBeforeList = [];
                if (flag == 1) {
                    this.formCustom = data.row;
                    this.getCoverFile();
                    this.getFiles();
                    this.formCustom.createDate = this.formatDate(new Date(this.formCustom.createDate), 'yyyy-MM-dd');
                    this.formCustom.updateDate = this.formatDate(new Date(this.formCustom.updateDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {
                    //修改页面
                    this.add = false;
                    this.formCustom = JSON.parse(JSON.stringify(data.row));
                    this.getCoverFile();
                    this.getFiles();
                    this.$nextTick(function() {
                        this.$refs.myTextEditor.quill.blur();
                        this.$refs.modal1Ref.scrollTop = 0;
                    });
                    this.formCustom.updateDate = this.formatDate(new Date(this.formCustom.updateDate), 'yyyy-MM-dd');
                    this.model1 = true;
                }
            },
            deleteContentFile(name){
                for(var index = 0;index<this.uploadList.length;)
                {
                    if(this.uploadBeforeList[index].id == name){
                        this.uploadBeforeList.splice(index,1);
                        this.uploadFileDeleteList.push(id);
                    }
                    else
                        index++;
                }
            },
            deleteCoverFile(id){
                for(var index = 0;index<this.coverFileList.length;)
                {
                    if(this.coverFileList[index].id == id){
                        this.coverFileList.splice(index,1);
                        this.coverFileDeleteList.push(id);
                    }
                    else
                        index++;
                }
            },
            coverFileDel(){
                this.coverFileDeleteList.forEach(item=>{
                    this.$http.delete(Api.downloadMongoFile + '/' + item).then((res) => {
                    }).catch(e => {
                        
                    }); 
                })
            },
            contentFileDel(){
                this.uploadFileDeleteList.forEach(item=>{
                    
                    this.$http.post(Api.deleteVideo + "?filePath" + item.videoPath).then((res) => {

                    }).catch(e => {
                       
                    }); 
                })
            },
            deleteData(params) {
                let istrue = confirm("是否确定删除?");
                if (istrue) {
                    this.$http.delete(Api.safeActivityMonth + '/' + params.row.safeActivityMonthId).then((res) => {
                        if (res.data.status == 200) {
                            this.$Message.info('删除成功');
                            this.query();
                        } else {
                            this.$Message.info('删除失败');
                        }
                    }).catch(e => {
                        this.$Message.error("修改失败");
                    });
                }
            },
            verifyData(data){
                this.formCustom = data;
                this.getCoverFile();
                this.getFiles();
                this.formCustom.createDate = this.formatDate(new Date(this.formCustom.createDate), 'yyyy-MM-dd');    
                this.model3 = true;
            },
            reject(){
                this.formCustom.isTop = '0';
                this.formCustom.isPass = '0';
                this.$http.put(Api.safeActivityMonth, this.formCustom).then((res) => {
                    this.$Message.success("保存成功")
                    this.model3 = false;
                    this.query();
                }).catch(e => {
                    this.model3 = false;
                    this.query();
                    this.$Message.error("数据获取失败")
                })
            },
            recallData(data){
                this.formCustom.isTop = '0';
                this.formCustom.isPass = '0';
                this.$http.put(Api.safeActivityMonth, this.formCustom).then((res) => {
                    this.$Message.success("保存成功")
                    this.model3 = false;
                    this.query();
                }).catch(e => {
                    this.model3 = false;
                    this.query();
                    this.$Message.error("数据获取失败")
                })
            },
            examine(){
                this.formCustom.isTop = '0';
                this.formCustom.isPass = '1';
                this.$http.put(Api.safeActivityMonth, this.formCustom).then((res) => {
                    this.$Message.success("保存成功")
                    this.model3 = false;
                    this.query();
                }).catch(e => {
                    this.model3 = false;
                    this.query();
                    this.$Message.error("数据获取失败")
                })
            },
            examineTop(){
                this.formCustom.isTop = '1';
                this.formCustom.isPass = '1';
                this.$http.put(Api.safeActivityMonth, this.formCustom).then((res) => {
                    this.$Message.success("保存成功")
                    this.model3 = false;
                    this.query();
                }).catch(e => {
                    this.model3 = false;
                    this.query();
                    this.$Message.error("数据获取失败")
                })
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
